package com.miaosha.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.miaosha.dao.ProductDOMapper;
import com.miaosha.dao.ProductStockDOMapper;
import com.miaosha.dao.PromoDOMapper;
import com.miaosha.dataobject.ProductDO;
import com.miaosha.dataobject.ProductStockDO;
import com.miaosha.dataobject.PromoDO;
import com.miaosha.error.EnumError;
import com.miaosha.error.ErrorException;
import com.miaosha.model.ProductModel;
import com.miaosha.model.PromoModel;
import com.miaosha.service.ProductService;
import com.miaosha.service.PromoService;
import com.miaosha.validator.ValidationResult;
import com.miaosha.validator.ValidatorImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService{

    @Autowired
    private ValidatorImpl validator;

    @Autowired
    private ProductDOMapper productDOMapper;

    @Autowired
    private ProductStockDOMapper productStockDOMapper;

    @Autowired
    private PromoService promoService;

    @Override
    @Transactional
    public ProductModel createProduct(ProductModel productModel) throws ErrorException {
        // 校验入参
        ValidationResult validationResult = validator.validation(productModel);
        if (validationResult.isHasError()){
            throw new ErrorException(EnumError.PARAMETER_VALIDATION_ERROR, validationResult.getErrorMessage());
        }

        // 转化model--->DataObject
        ProductDO productDO = convertProductDOFromProductModel(productModel);
        if (productDO == null){
            throw new ErrorException(EnumError.PARAMETER_VALIDATION_ERROR);
        }

        // 写入数据库
        productDOMapper.insertSelective(productDO);
        productModel.setId(productDO.getId());

        // 写入库存
        ProductStockDO productStockDO = convertProductStockDOFromProductModel(productModel);
        productStockDOMapper.insertSelective(productStockDO);

        // 返回创建完成的对象
        return getProductDetailById(productModel.getId());
    }

    @Override
    public List<ProductModel> getProductList() {
        PageHelper.startPage(1 , 5);
        List<ProductDO> productDOList = productDOMapper.getProductList();
        List<ProductModel> productModelList = productDOList.stream().map(productDO -> {
            ProductStockDO productStockDO = productStockDOMapper.selectByProductId(productDO.getId());
            ProductModel productModel = convertProductModelFromProductDo(productDO, productStockDO);
            return productModel;
        }).collect(Collectors.toList());
        //得到分页的结果对象
        PageInfo<ProductModel> productModelPageInfo = new PageInfo<>(productModelList);
        //得到分页中的person条目对象
        List<ProductModel> pageList = productModelPageInfo.getList();
        return pageList;
    }

    @Override
    public ProductModel getProductDetailById(Integer productId) throws ErrorException {
        if (productId == null) return null;
        ProductDO productDO = productDOMapper.selectByPrimaryKey(productId);
        if (productDO == null){
            return null;
        }
        // 操作获得库存
        ProductStockDO productStockDO = productStockDOMapper.selectByProductId(productDO.getId());

        // 转化DataObject ---> Model
        ProductModel productModel = convertProductModelFromProductDo(productDO, productStockDO);

        // 获取活动信息
        PromoModel promoModel = promoService.getPromoByProductId(productModel.getId());
        if (promoModel != null && promoModel.getStatus() != 3){
            productModel.setPromoModel(promoModel);
        }

        return productModel;
    }

    @Override
    @Transactional
    public boolean decreaseStock(Integer productId, Integer amount) throws ErrorException {
        int affectedRow = productStockDOMapper.decreaseStock(productId, amount);
        if (affectedRow > 0){
            // 更新库存成功
            return true;
        }
        // 更新库存失败
        return false;
    }

    @Override
    @Transactional
    public void increaseSales(Integer productId, Integer amount) throws ErrorException {
        productDOMapper.increaseSales(productId, amount);
    }

    private ProductDO convertProductDOFromProductModel(ProductModel productModel){
        if (productModel == null) return null;
        ProductDO productDO = new ProductDO();
        BeanUtils.copyProperties(productModel, productDO);
        productDO.setPrice(productModel.getPrice().doubleValue());
        return productDO;
    }

    private ProductStockDO convertProductStockDOFromProductModel(ProductModel productModel){
        if (productModel == null) return null;
        ProductStockDO productStockDO = new ProductStockDO();
        productStockDO.setProductId(productModel.getId());
        productStockDO.setStock(productModel.getStock());
        return productStockDO;
    }

    private ProductModel convertProductModelFromProductDo(ProductDO productDO, ProductStockDO productStockDO){
        if (productDO == null) return null;
        ProductModel productModel = new ProductModel();
        BeanUtils.copyProperties(productDO, productModel);
        productModel.setPrice(new BigDecimal(productDO.getPrice()));
        productModel.setStock(productStockDO.getStock());
        return productModel;
    }
}
